package com.dianrui.operation.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RideStep;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.route.WalkStep;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.SecretProtocolAdapter;
import com.dianrui.operation.bean.BikePointModel;
import com.dianrui.operation.bean.Colleage;
import com.dianrui.operation.bean.Inspection;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.ActionItem;
import com.dianrui.operation.util.CountDownTimerUtils;
import com.dianrui.operation.util.JsonUtils;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.TitlePopup;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.Packet;
import com.tbit.tbitblesdk.protocol.callback.PacketCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;
import com.xiaoantech.sdk.XiaoanBleApiClient;
import com.xiaoantech.sdk.ble.model.Response;
import com.xiaoantech.sdk.listeners.BleCallback;
import com.xiaoantech.sdk.listeners.BleStateChangeListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 巡检
 */
public class VehicleInspectionActivity extends BaseActivity implements AMapLocationListener{

    private String mTitles;
    private Marker clickMaker;
    private AMap aMap;
    private LatLng latLng;
    private boolean isFirstLoc = true;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private List<Inspection> inspectionsList = new ArrayList<>();
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private List<Colleage> colleageList = new ArrayList<>();
    private List<LatLng> mAreaPoints = new ArrayList<>();
    private BluetoothAdapter mBlueadapter;
    private BitmapDescriptor bitD_ToubleCarEle;//故障车的maker
    private BitmapDescriptor bitD_outsideCarEle;//出界车的maker
    private BitmapDescriptor bitD_timeoutCarEle;//超时车的maker
    private BitmapDescriptor bitD_IllegalCarEle;//违停车的maker
    private BitmapDescriptor bitD_offlineCarEle;//离线车的maker
    private BitmapDescriptor bitD_NoStop;
    private BitmapDescriptor bitD_Stop;//停止
    private BitmapDescriptor bitD_Start;
    private BitmapDescriptor bitD_Pause;
    private BitmapDescriptor bitD_LowCarEle;
    private TitlePopup titlePopup;
    private double currentLatitude;
    private double currentLongitude;
    public String CUSTOMMARKER = "Markers";
    public String COLLEGAEMMARKER = "Colleage";
    private XiaoanBleApiClient apiClient;
    private XiaoanBleApiClient.Builder builder;
    private ViewPager viewPager;
    private LinearLayout viewgroup;
    private List<String> titlesArray = new ArrayList<>();
    private LoadPageAdapter loadPageAdapter;
    private ImageView[] imageViews;
    private ImageView imageView;
    private List<Marker> mAllCollegeMarker = new ArrayList<>();
    private List<Marker> mAllCarMarker = new ArrayList<>();//marker集合。分类的话通过这个集合里marker全部移除再把整个list清除，这样就算不在地图外的markker给干掉


    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;
    @BindView(R.id.all_txt)
    TextView allTxt;
    @BindView(R.id.all_line)
    View allLine;
    @BindView(R.id.trouble_txt)
    TextView troubleTxt;
    @BindView(R.id.trouble_line)
    View troubleLine;
    @BindView(R.id.outside_txt)
    TextView outsideTxt;
    @BindView(R.id.outside_line)
    View outsideLine;
    @BindView(R.id.timeout_txt)
    TextView timeoutTxt;
    @BindView(R.id.timeout_line)
    View timeoutLine;
    @BindView(R.id.Illegalstop_txt)
    TextView IllegalstopTxt;
    @BindView(R.id.Illegalstop_line)
    View IllegalstopLine;
    @BindView(R.id.offline_txt)
    TextView offlineTxt;
    @BindView(R.id.offline_line)
    View offlineLine;
    @BindView(R.id.top_right_imgs)
    ImageView topRightImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mapviews)
    MapView mapviews;
    @BindView(R.id.colleagebtn)
    Button colleagebtn;

    private int currentStatus = 1;


    @Override
    public int getContentViewId() {
        return R.layout.activity_vehicle_inspection;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }

    @Override
    public void initView() {
        TbitBle.initialize(VehicleInspectionActivity.this, new SecretProtocolAdapter());
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
                title.setText(mTitles);
            }
        }
        aMap = mapviews.getMap();

        topRightImg.setImageResource(R.mipmap.changbattery_qr_code);
        topRightImg.setVisibility(View.VISIBLE);

        builder = new XiaoanBleApiClient.Builder(this);
        apiClient = builder.build();

        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。


        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setOnInfoWindowClickListener(listener);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMaker != null && clickMaker.isInfoWindowShown()) {
                    clickMaker.hideInfoWindow();

                }
            }
        });
        loadLocation();
        loadMarker();
        loadTitlePop();

    }

    private void loadLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(VehicleInspectionActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(VehicleInspectionActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }
    }

    //初始化marker
    private void loadMarker() {
        View stopview = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.stopstatus_point, null);
        bitD_Stop = BitmapDescriptorFactory.fromView(stopview);

        View startView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_green_point, null);
        bitD_Start = BitmapDescriptorFactory.fromView(startView);

        View nopauseView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.pause_point, null);
        bitD_Pause = BitmapDescriptorFactory.fromView(nopauseView);

        View lowPowerView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_red_point, null);
        bitD_LowCarEle = BitmapDescriptorFactory.fromView(lowPowerView);

        View toubleCarView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.trouble_point, null);

        bitD_ToubleCarEle = BitmapDescriptorFactory.fromView(toubleCarView);

        View outsideView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.outside_point, null);

        bitD_outsideCarEle = BitmapDescriptorFactory.fromView(outsideView);

        View timeoutView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.timeout_point, null);

        bitD_timeoutCarEle = BitmapDescriptorFactory.fromView(timeoutView);


        View IllegalCarView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.illegalcar_point, null);

        bitD_IllegalCarEle = BitmapDescriptorFactory.fromView(IllegalCarView);

        View offlineCarView = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.offlinecar_point, null);

        bitD_offlineCarEle = BitmapDescriptorFactory.fromView(offlineCarView);

        View nostopview1 = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop = BitmapDescriptorFactory.fromView(nostopview1);
    }




    private void loadTitlePop() {
        String[] texts = {"扫一扫", "输入编码"};
        List<ActionItem> list = new ArrayList<>();
        ActionItem bean = null;
        for (int i = 0; i < texts.length; i++) {
            bean = new ActionItem();
            bean.setText(texts[i]);
            list.add(bean);
        }
        titlePopup = new TitlePopup(this, list);
        titlePopup.setOnItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        titlePopup.dismiss();
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (ContextCompat.checkSelfPermission(VehicleInspectionActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                                Intent intent = new Intent(VehicleInspectionActivity.this, OpeationCaptureActivity.class);
                                intent.putExtra("camflag", "8");
                                startActivityForResult(intent, 108);
                            } else {
                                ActivityCompat.requestPermissions(VehicleInspectionActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                            }
                        } else {
                            Intent intent = new Intent(VehicleInspectionActivity.this, OpeationCaptureActivity.class);
                            intent.putExtra("camflag", "8");
                            startActivityForResult(intent, 108);
                        }
                        break;
                    case 1:
                        titlePopup.dismiss();
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(VehicleInspectionActivity.this, R.style.RcDialog);
                        View view2 = LayoutInflater.from(VehicleInspectionActivity.this).inflate(R.layout.dialog_code, null);
                        final AlertDialog dialog1 = builder1.create();
                        dialog1.setView(view2);
                        final TextView yes_dialog = view2.findViewById(R.id.yes_dialog_ask);
                        final TextView no_dialog = view2.findViewById(R.id.no_dialog_ask);
                        final EditText codeEdit = view2.findViewById(R.id.code_edit);

                        yes_dialog.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (StringUtils.isEmpty(codeEdit.getText().toString())) {
                                    ToastUtil.showToast(getString(R.string.code_txt_title));
                                } else {
                                    dialog1.dismiss();
                                    getCarinfo(codeEdit.getText().toString());
                                }

                            }
                        });
                        no_dialog.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog1.dismiss();

                            }
                        });
                        dialog1.show();
                        break;

                    default:
                        break;
                }
            }
        });


    }

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void initData() {}

    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (bitD_Stop != null) {
            bitD_Stop.recycle();
            bitD_Stop=null;
        }
        if (bitD_Start != null) {
            bitD_Start.recycle();
            bitD_Start=null;
        }
        if (bitD_Pause != null) {
            bitD_Pause.recycle();
            bitD_Pause=null;
        }
        if (bitD_LowCarEle != null) {
            bitD_LowCarEle.recycle();
            bitD_LowCarEle=null;
        }
        if (bitD_ToubleCarEle != null) {
            bitD_ToubleCarEle.recycle();
            bitD_ToubleCarEle=null;
        }
        if (bitD_IllegalCarEle != null) {
            bitD_IllegalCarEle.recycle();
            bitD_IllegalCarEle=null;
        }
        if (bitD_outsideCarEle != null) {
            bitD_outsideCarEle.recycle();
            bitD_outsideCarEle=null;
        }
        if (bitD_timeoutCarEle != null) {
            bitD_timeoutCarEle.recycle();
            bitD_timeoutCarEle=null;
        }
        if (bitD_NoStop != null) {
            bitD_NoStop.recycle();
            bitD_NoStop=null;
        }
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
        TbitBle.destroy();
        TbitBle.disConnect();
        if (apiClient != null) {
            apiClient.disConnect();
            apiClient.onDestroy();
        }
        if (viewPager != null) {
            viewPager.removeAllViews();
            viewPager.removeOnPageChangeListener(null);
        }
        if (colleageList != null) {
            colleageList.clear();
            colleageList = null;
        }
        if (mAllCollegeMarker != null) {
            mAllCollegeMarker.clear();
            mAllCollegeMarker = null;
        }
        if (mAllCarMarker != null) {
            mAllCarMarker.clear();
            mAllCarMarker = null;
        }
        viewgroup = null;
    }

    private int tagClick;
    private int pressFlag = 0;

    @OnClick({R.id.all_layout, R.id.back, R.id.bigger, R.id.smaller, R.id.refresh, R.id.location, R.id.top_right_imgs, R.id.trouble_layout, R.id.outside_layout,
            R.id.colleagebtn,
            R.id.timeout_layout, R.id.Illegalstop_layout, R.id.offline_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.top_right_imgs:
                titlePopup.showPopupWindow(view);
                break;

            case R.id.all_layout:
                tagClick = 0;
                allClick();
                currentStatus = 1;
                break;

            case R.id.trouble_layout:
                tagClick = 1;
                troubleClick();
                currentStatus = 5;
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollTo(-186, 0);
                    }
                });
                break;

            case R.id.outside_layout:
                tagClick = 2;
                outsideClick();
                currentStatus = 6;
                break;

            case R.id.timeout_layout:
                tagClick = 3;
                timeOutClick();
                currentStatus = 7;
                break;

            case R.id.Illegalstop_layout:
                tagClick = 4;
                illgegalStopClick();
                currentStatus = 8;
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollTo(186, 0);
                    }
                });
                break;

            case R.id.offline_layout:
                tagClick = 5;
                currentStatus = 9;
                offLineClick();
                break;

            case R.id.location:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                getNearCar(latLng, true, currentStatus);
                break;

            case R.id.refresh:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLatitude, currentLongitude)));
                break;

            case R.id.bigger:
                MyUtil.setMapStatus(mapviews, MyUtil.getZoom(mapviews) - 1);
                break;
            case R.id.smaller:
                MyUtil.setMapStatus(mapviews, MyUtil.getZoom(mapviews) + 1);
                break;
            case R.id.colleagebtn:
                if (pressFlag == 0) {
                    Colleage();
                    colleagebtn.setText("关闭同事位置");
                    pressFlag = 1;
                } else {
                    colleagebtn.setText("显示同事位置");
                    clearCollegeMarkers();
                    pressFlag = 0;
                }
                break;

            default:
                break;
        }
    }

    /**
     * 全部
     */
    private void allClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.red));
        allLine.setVisibility(View.VISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.black));
        troubleLine.setVisibility(View.INVISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.black));
        outsideLine.setVisibility(View.INVISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.black));
        timeoutLine.setVisibility(View.INVISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.black));
        IllegalstopLine.setVisibility(View.INVISIBLE);
        offlineTxt.setTextColor(getResources().getColor(R.color.black));
        offlineLine.setVisibility(View.INVISIBLE);

        for (int i = 0; i < inspectionsList.size(); i++) {
            if ("1".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Stop);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("2".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Start);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("3".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Pause);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("4".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_LowCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("5".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_ToubleCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }
            if ("6".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_outsideCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("7".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_timeoutCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("8".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_IllegalCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }

            if ("9".equals(inspectionsList.get(i).vehicle_status)) {
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_offlineCarEle);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCarMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(inspectionsList.get(i));
            }
        }
    }

    /**
     * 故障 marker刷新
     */
    private void troubleClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.black));
        allLine.setVisibility(View.INVISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.red));
        troubleLine.setVisibility(View.VISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.black));
        outsideLine.setVisibility(View.INVISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.black));
        timeoutLine.setVisibility(View.INVISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.black));
        IllegalstopLine.setVisibility(View.INVISIBLE);

        offlineTxt.setTextColor(getResources().getColor(R.color.black));
        offlineLine.setVisibility(View.INVISIBLE);


        for (int i = 0; i < inspectionsList.size(); i++) {
            switch (inspectionsList.get(i).vehicle_status) {
                case "5":
                    MarkerOptions markerOptions1 = new MarkerOptions();
                    markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_ToubleCarEle);
                    Marker marker = aMap.addMarker(markerOptions1);
                    mAllCarMarker.add(marker);
                    marker.setTitle(CUSTOMMARKER);
                    marker.setObject(inspectionsList.get(i));
            }
        }
    }

    /**
     * 出界 marker刷新
     */
    private void outsideClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.black));
        allLine.setVisibility(View.INVISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.black));
        troubleLine.setVisibility(View.INVISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.red));
        outsideLine.setVisibility(View.VISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.black));
        timeoutLine.setVisibility(View.INVISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.black));
        IllegalstopLine.setVisibility(View.INVISIBLE);

        offlineTxt.setTextColor(getResources().getColor(R.color.black));
        offlineLine.setVisibility(View.INVISIBLE);

        for (int i = 0; i < inspectionsList.size(); i++) {
            switch (inspectionsList.get(i).vehicle_status) {
                case "6":
                    MarkerOptions markerOptions1 = new MarkerOptions();
                    markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_outsideCarEle);
                    Marker marker = aMap.addMarker(markerOptions1);
                    mAllCarMarker.add(marker);
                    marker.setTitle(CUSTOMMARKER);
                    marker.setObject(inspectionsList.get(i));
                    break;
            }

        }
    }

    /**
     * 超时 marker刷新
     */
    private void timeOutClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.black));
        allLine.setVisibility(View.INVISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.black));
        troubleLine.setVisibility(View.INVISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.black));
        outsideLine.setVisibility(View.INVISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.red));
        timeoutLine.setVisibility(View.VISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.black));
        IllegalstopLine.setVisibility(View.INVISIBLE);

        offlineTxt.setTextColor(getResources().getColor(R.color.black));
        offlineLine.setVisibility(View.INVISIBLE);

        for (int i = 0; i < inspectionsList.size(); i++) {
            switch (inspectionsList.get(i).vehicle_status) {
                case "7":
                    MarkerOptions markerOptions1 = new MarkerOptions();
                    markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_timeoutCarEle);
                    Marker marker = aMap.addMarker(markerOptions1);
                    mAllCarMarker.add(marker);
                    marker.setTitle(CUSTOMMARKER);
                    marker.setObject(inspectionsList.get(i));
                    break;
            }
        }
    }

    /**
     * 违停
     */
    private void illgegalStopClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.black));
        allLine.setVisibility(View.INVISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.black));
        troubleLine.setVisibility(View.INVISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.black));
        outsideLine.setVisibility(View.INVISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.black));
        timeoutLine.setVisibility(View.INVISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.red));
        IllegalstopLine.setVisibility(View.VISIBLE);
        offlineTxt.setTextColor(getResources().getColor(R.color.black));
        offlineLine.setVisibility(View.INVISIBLE);

        for (int i = 0; i < inspectionsList.size(); i++) {
            switch (inspectionsList.get(i).vehicle_status) {
                case "8":
                    MarkerOptions markerOptions1 = new MarkerOptions();
                    markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_IllegalCarEle);
                    Marker marker = aMap.addMarker(markerOptions1);
                    mAllCarMarker.add(marker);
                    marker.setTitle(CUSTOMMARKER);
                    marker.setObject(inspectionsList.get(i));
                    break;
                default:
                    break;

            }
        }
    }

    /**
     * 离线marker 刷新
     */
    private void offLineClick() {
        clearMarkers();
        allTxt.setTextColor(getResources().getColor(R.color.black));
        allLine.setVisibility(View.INVISIBLE);
        troubleTxt.setTextColor(getResources().getColor(R.color.black));
        troubleLine.setVisibility(View.INVISIBLE);
        outsideTxt.setTextColor(getResources().getColor(R.color.black));
        outsideLine.setVisibility(View.INVISIBLE);
        timeoutTxt.setTextColor(getResources().getColor(R.color.black));
        timeoutLine.setVisibility(View.INVISIBLE);
        IllegalstopTxt.setTextColor(getResources().getColor(R.color.black));
        IllegalstopLine.setVisibility(View.INVISIBLE);
        offlineTxt.setTextColor(getResources().getColor(R.color.red));
        offlineLine.setVisibility(View.VISIBLE);


        for (int i = 0; i < inspectionsList.size(); i++) {
            if ("9".equals(inspectionsList.get(i).vehicle_status)) {
                switch (inspectionsList.get(i).vehicle_status) {
                    case "9":
                        MarkerOptions markerOptions1 = new MarkerOptions();
                        markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_offlineCarEle);
                        Marker marker = aMap.addMarker(markerOptions1);
                        mAllCarMarker.add(marker);
                        marker.setTitle(CUSTOMMARKER);
                        marker.setObject(inspectionsList.get(i));
                        break;
                }

            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            currentLatitude = aMapLocation.getLatitude();
            currentLongitude = aMapLocation.getLongitude();
            latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            if (isFirstLoc) {
                getStation(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                getNearCar(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()), false, 1);
                isFirstLoc = false;

            }
        }
    }

    //获取网点
    private void getStation(LatLng latLng) {
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("type_id", "2");
        networksJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        networksJsonobject.addProperty("radius", "0");//周边范围：默认1公里或者0公里,
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.GETNETWORK_BIKE, networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (null != jsonObject && !isFinishing()) {
                        if (bikePointList != null) {
                            bikePointList.clear();
                        }
                        if (mAreaPoints != null) {
                            mAreaPoints.clear();
                        }
                        if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                            JSONObject jsonObject2 = jsonObject.optJSONObject("area");
                            if (jsonObject.optString("data").equals("{}")) {
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                            } else if (jsonObject.optString("data").equals("[]")) {
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                            } else {
                                JSONArray gfixed_path = jsonObject.optJSONObject("area").optJSONArray("gfixed_path");
                                if (gfixed_path.length() > 0) {
                                    for (int j = 0; j < gfixed_path.length(); j++) {
                                        JSONObject jsonObject3 = gfixed_path.optJSONObject(j);
                                        mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                                    }
                                    if (mAreaPoints.size() > 0) {
                                        PolygonOptions polygonOptions = new PolygonOptions();
                                        polygonOptions.addAll(mAreaPoints);
                                        polygonOptions.strokeWidth(4);
                                        polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                                        polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                                        aMap.addPolygon(polygonOptions);
                                    }
                                    LatLngBounds.Builder b = LatLngBounds.builder();

                                    for (LatLng latLng : mAreaPoints) {
                                        b.include(latLng);
                                    }
                                    LatLngBounds bounds = b.build();
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 130, 130, 580, 260));
                                }

                            }
                            JSONArray jsonArray = jsonObject.optJSONArray("data");
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    BikePointModel bikeModel = new BikePointModel();
                                    bikeModel.blat = jsonArray.optJSONObject(i).optDouble("glat");
                                    bikeModel.blng = jsonArray.optJSONObject(i).optDouble("glng");
                                    bikeModel.vehicle_number = jsonArray.optJSONObject(i).optString("vehicle_number");
                                    bikePointList.add(bikeModel);

                                    if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                        List<LatLng> points = new ArrayList<>();
                                        if (points != null) {
                                            points.clear();
                                        }
                                        JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                        if (jsonArray3.length() > 0) {
                                            for (int j = 0; j <= jsonArray3.length(); j++) {
                                                if (j == jsonArray3.length()) {
                                                    JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                    points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                } else {
                                                    JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                    points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                }
                                            }

                                            if (points.size() < 2) {
                                                return;
                                            }
                                            if (jsonArray.optJSONObject(i).optString("is_forbid").equals("1")) {
                                                aMap.addPolyline((new PolylineOptions()).addAll(points).width(4).setDottedLine(true).color(Color.RED));
                                                MarkerOptions markerOptions1 = new MarkerOptions();
                                                markerOptions1.position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng)).icon(bitD_NoStop);
                                                Marker marker = aMap.addMarker(markerOptions1);

                                            } else {
                                                List<BitmapDescriptor> textureList = new ArrayList<>();
                                                textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                List<Integer> textureIndexs = new ArrayList<>();
                                                textureIndexs.add(i);
                                                List<LatLng> overLatlngList = new ArrayList<>(points);

                                                PolylineOptions polylineOptions = new PolylineOptions();
                                                polylineOptions.addAll(overLatlngList);
                                                polylineOptions.width(4);
                                                polylineOptions.setCustomTextureList(textureList);
                                                polylineOptions.setCustomTextureIndex(textureIndexs);
                                                polylineOptions.setDottedLine(true);
                                                polylineOptions.setUseTexture(true);
                                                aMap.addPolyline(polylineOptions);
                                            }
                                        }


                                    } else if ("0".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                        int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                        aMap.addCircle(new CircleOptions()
                                                .center(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng))
                                                .radius(networkRange)
                                                .fillColor(Color.argb(46, 64, 194, 134)).strokeWidth(4).strokeColor(Color.argb(46, 64, 194, 134)));
                                    }
                                }
                            }
                        } else if ("1001".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1002".equals(jsonObject.optString("status"))) {
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    @SuppressLint("SetTextI18n")
    private void getNearCar(LatLng latLng, boolean isRfresh, final int currentStatus) {//获取附近车辆
        if (isRfresh) {
            showLoadingDialog("正在刷新");
        }
        JsonObject nearJsonobject = new JsonObject();
        nearJsonobject.addProperty("type_id", "2");
        nearJsonobject.addProperty("type", "1");
        nearJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        nearJsonobject.addProperty("radius", "0");
        nearJsonobject.addProperty("status", "4,5,6");
        StringBuilder nearBikeBuilder = new StringBuilder();
        nearBikeBuilder.append(SharedUtil.getUrl()).append(Url.NEARBIKE);
        XHttpRequest.getInstance().postRequests(nearBikeBuilder.toString(), nearJsonobject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    if (isFinishing()) {
                        return;
                    }
                    String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                    if (Constant.DATASUCCESS.equals(status)) {
                        dismissLoadingDialog();
                        String data = JsonUtils.getJsonStr(result, "data");
                        if (inspectionsList != null) {
                            inspectionsList.clear();
                        }
                        if (!StringUtils.isEmpty(data)) {
                            List<Inspection> inspectionLists = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<Inspection>>() {
                            }.getType());
                            if (inspectionLists != null && inspectionLists.size() > 0) {
                                inspectionsList.addAll(inspectionLists);
                            }
                            int troublecounts = 0;
                            int outsidecounts = 0;
                            int timeoutcounts = 0;
                            int illstopcounts = 0;
                            int offlinecarcounts = 0;

                            for (Inspection inspection : inspectionsList) {
                                if ("5".equals(inspection.vehicle_status)) {
                                    troublecounts = troublecounts + 1;

                                }

                                if ("6".equals(inspection.vehicle_status)) {
                                    outsidecounts = outsidecounts + 1;
                                }

                                if ("7".equals(inspection.vehicle_status)) {
                                    timeoutcounts = timeoutcounts + 1;

                                }
                                if ("8".equals(inspection.vehicle_status)) {
                                    illstopcounts = illstopcounts + 1;
                                }

                                if ("9".equals(inspection.vehicle_status)) {
                                    offlinecarcounts = offlinecarcounts + 1;
                                }
                            }
                            if (troublecounts > 0) {
                                troubleTxt.setText(getString(R.string.troublecar) + "(" + troublecounts + "" + ")");
                            } else {
                                troubleTxt.setText(getString(R.string.troublecar));
                            }

                            if (outsidecounts > 0) {
                                outsideTxt.setText(getString(R.string.ouside_txt) + "(" + outsidecounts + "" + ")");
                            } else {
                                outsideTxt.setText(getString(R.string.ouside_txt));
                            }

                            if (timeoutcounts > 0) {
                                timeoutTxt.setText(getString(R.string.timeoutcar) + "(" + timeoutcounts + "" + ")");
                            } else {
                                timeoutTxt.setText(getString(R.string.timeoutcar));
                            }

                            if (illstopcounts > 0) {
                                IllegalstopTxt.setText(getString(R.string.nostopscar) + "(" + illstopcounts + "" + ")");
                            } else {
                                IllegalstopTxt.setText(getString(R.string.nostopscar));
                            }

                            if (offlinecarcounts > 0) {
                                offlineTxt.setText(getString(R.string.offlinecar) + "(" + offlinecarcounts + "" + ")");
                            } else {
                                offlineTxt.setText(getString(R.string.offlinecar));
                            }

                            title.setText(mTitles + "(" + inspectionsList.size() + ")");

                            switch (currentStatus) {
                                case 1:
                                    //默认显示全部的
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("1".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Stop).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("2".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Start).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("3".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_Pause).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("4".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_LowCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("5".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_ToubleCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }
                                        if ("6".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_outsideCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("7".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_timeoutCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("8".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_IllegalCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                        if ("9".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_offlineCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }
                                    }
                                    break;
                                case 5:
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("5".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_ToubleCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                    }
                                    break;
                                case 6:
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("6".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_outsideCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }

                                    }
                                    break;

                                case 7:
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("7".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_timeoutCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }
                                    }
                                    break;
                                case 8:
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("8".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_IllegalCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }
                                    }
                                    break;

                                case 9:
                                    for (int i = 0; i < inspectionsList.size(); i++) {
                                        if ("9".equals(inspectionsList.get(i).vehicle_status)) {
                                            MarkerOptions markerOptions1 = new MarkerOptions();
                                            markerOptions1.position(new LatLng(inspectionsList.get(i).glat, inspectionsList.get(i).glng)).icon(bitD_offlineCarEle).zIndex(99);
                                            Marker marker = aMap.addMarker(markerOptions1);
                                            mAllCarMarker.add(marker);
                                            marker.setTitle(CUSTOMMARKER);
                                            marker.setObject(inspectionsList.get(i));
                                        }
                                    }
                                    break;

                                default:
                                    break;
                            }


                        }
                    } else if ("1001".equals(status)) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                    } else if ("1002".equals(status)) {
                        dismissLoadingDialog();
                        spUtils.clear();
                        ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                        JumpActivitys(LoginActivity.class);
                        finish();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15));
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //获取同事位置
    //TODO
    public void Colleage() {
        StringBuilder colleageBulider = new StringBuilder();
        colleageBulider.append(SharedUtil.getUrl()).append(Url.COLLEAGES);
        XHttpRequest.getInstance().postRequests(colleageBulider.toString(), "", new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    if (isFinishing()) {
                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            if (colleageList != null) {
                                colleageList.clear();
                            }
                            JSONArray jsonArray = jsonObject.optJSONArray("data");
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    Colleage colleage = new Colleage();
                                    colleage.glat = jsonArray.optJSONObject(i).optDouble("glat");
                                    colleage.glng = jsonArray.optJSONObject(i).optDouble("glng");
                                    colleage.nickname = jsonArray.optJSONObject(i).optString("nickname");
                                    colleage.face = jsonArray.optJSONObject(i).optString("face");
                                    colleage.mobile = jsonArray.optJSONObject(i).optString("mobile");
                                    colleage.working_state = jsonArray.optJSONObject(i).optString("working_state");
                                    colleageList.add(colleage);
                                }
                                for (int i = 0; i < colleageList.size(); i++) {
                                    final MarkerOptions markerOption = new MarkerOptions();
                                    markerOption.position(new LatLng(colleageList.get(i).glat, colleageList.get(i).glng)).zIndex(100);
                                    final View view = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.colleagepoint, null);
                                    final ImageView colleage_img = view.findViewById(R.id.colleage_img);
                                    try {
                                        final int finalI = i;
                                        SimpleTarget locationTarget = new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                colleage_img.setImageBitmap(resource);
                                                Bitmap bitmap = getViewBitmap(view);
                                                markerOption.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
                                                Marker marker = aMap.addMarker(markerOption);
                                                mAllCollegeMarker.add(marker);
                                                marker.setObject(colleageList.get(finalI));
                                                marker.setTitle(COLLEGAEMMARKER);
                                                marker.setMarkerOptions(markerOption);
                                            }
                                        };

                                        RequestBuilder lRequestBuilder = Glide.with(getApplication())
                                                .asBitmap()
                                                .load(colleageList.get(i).face).apply(new RequestOptions()
                                                        .transforms(new RoundedCorners(800)));

                                        lRequestBuilder.into(locationTarget);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }


                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void failedRequest(String result) {
            }
        });
    }

    public Bitmap getViewBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        return Bitmap.createBitmap(view.getDrawingCache());
    }

    /**
     * 清除所有同事Marker
     */
    private void clearMarkers() {
        if (mAllCarMarker.size() > 0) {
            for (Marker marker : mAllCarMarker) {
                marker.remove();
            }
            mAllCarMarker.clear();
        }
    }

    private void clearCollegeMarkers() {
        if (mAllCollegeMarker.size() > 0) {
            for (Marker marker : mAllCollegeMarker) {
                marker.remove();
            }
            mAllCollegeMarker.clear();
        }
    }

    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker marker) {
            clickMaker = marker;
            marker.showInfoWindow();
            return true;
        }
    };

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            if (marker.getTitle().equals("Colleage")) {
                View colleageView = LayoutInflater.from(VehicleInspectionActivity.this).inflate(R.layout.colleage_bubble, null);
                TextView name = colleageView.findViewById(R.id.name);
                TextView workstate = colleageView.findViewById(R.id.workstate);
                TextView mobile = colleageView.findViewById(R.id.mobile);
                final Colleage colleage = (Colleage) marker.getObject();

                StringBuilder nameBuilder = new StringBuilder();
                nameBuilder.append(getString(R.string.name)).append(colleage.nickname);
                name.setText(nameBuilder.toString());

                StringBuilder workstateuilder = new StringBuilder();
                workstateuilder.append(getString(R.string.workstate)).append(colleage.working_state);
                workstate.setText(workstateuilder.toString());


                StringBuilder mobileuilder = new StringBuilder();
                mobileuilder.append(getString(R.string.mobilenumber)).append(colleage.mobile);
                mobile.setText(mobileuilder.toString());

                mobile.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callPhone(colleage.mobile);
                    }
                });

                return colleageView;
            } else {
                View view = LayoutInflater.from(VehicleInspectionActivity.this).inflate(R.layout.inspection_bubble, null);
                final TextView number = view.findViewById(R.id.number);
                TextView carstatus = view.findViewById(R.id.carstatus);
                TextView battery = view.findViewById(R.id.battery);
                TextView rssi = view.findViewById(R.id.rssi);
                TextView carlocation = view.findViewById(R.id.carlocations);
                Button malfunction = view.findViewById(R.id.malfunction_btn);//故障车
                Button llegal = view.findViewById(R.id.llegal_btn);//违章车
                Button startdefense = view.findViewById(R.id.startdefense_btn);
                Button withdrawdevice = view.findViewById(R.id.withdrawdevice_btn);
                Button oppacc = view.findViewById(R.id.oppacc_btn);
                Button playBtn = view.findViewById(R.id.play_btn);
                Button gpsBtn = view.findViewById(R.id.gps_btn);
                Button closedevice = view.findViewById(R.id.close_btn);
                Button deviceRestart = view.findViewById(R.id.device_restart);
                Button nav = view.findViewById(R.id.nav_btn);
                final Inspection inspectioninfo = (Inspection) marker.getObject();

                StringBuilder carBuilder = new StringBuilder();
                carBuilder.append(getString(R.string.car_number_txt)).append(inspectioninfo.number);
                number.setText(carBuilder.toString());


                StringBuilder batteryBuilder = new StringBuilder();
                batteryBuilder.append("电量: ").append(inspectioninfo.battery).append("%");
                battery.setText(batteryBuilder.toString());

                StringBuilder statusNameBuilder = new StringBuilder();
                statusNameBuilder.append("车辆状态: ").append(inspectioninfo.status_name);
                carstatus.setText(statusNameBuilder.toString());

                StringBuilder rssiNameBuilder = new StringBuilder();
                rssiNameBuilder.append("信号强度: ").append(inspectioninfo.rssi);
                rssi.setText(rssiNameBuilder.toString());

                StringBuilder locationiString = new StringBuilder();
                locationiString.append("车辆地址:").append(inspectioninfo.city_path);
                if (!StringUtils.isEmpty(inspectioninfo.city_path)) {
                    carlocation.setText(locationiString.toString());
                } else {
                    carlocation.setText("车辆地址：无");
                }
                malfunction.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (inspectioninfo.maintain_id > 0) {
                            Intent intent = new Intent(VehicleInspectionActivity.this, FaultDetailsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("maintain_id", inspectioninfo.maintain_id);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(VehicleInspectionActivity.this, TroubleInfoCarActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("carnumber", inspectioninfo.number);
                            bundle.putString("address", inspectioninfo.city_path);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    }
                });
                llegal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (inspectioninfo.violation_id > 0) {
                            Intent intent = new Intent(VehicleInspectionActivity.this, ViolationDetailsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("violation_id", inspectioninfo.violation_id);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(VehicleInspectionActivity.this, BreakRuleInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("carnumber", inspectioninfo.number);
                            bundle.putString("address", inspectioninfo.city_path);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }

                    }
                });

                startdefense.setOnClickListener(new View.OnClickListener() {//启动
                    @Override
                    public void onClick(View v) {//启动
                        sendCommand(inspectioninfo.getNumber(), "1", "2", "1");
                    }
                });
                withdrawdevice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//撤防
                        sendCommand(inspectioninfo.getNumber(), "0", "3", "2");
                    }
                });
                closedevice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//关闭
                        sendCommand(inspectioninfo.getNumber(), "0", "2", "3");
                    }
                });

                oppacc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//开仓
                        sendCommand(inspectioninfo.getNumber(), "0", "5", "4");
                    }
                });

                playBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//播报
                        sendCommand(inspectioninfo.getNumber(), "0", "1", "5");
                    }
                });

                gpsBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//GPS重启
                        sendCommand(inspectioninfo.getNumber(), "0", "9", "");
                    }
                });

                deviceRestart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//设备重启
                        sendCommand(inspectioninfo.getNumber(), "0", "8", "");
                    }
                });
                nav.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(VehicleInspectionActivity.this, AMapNaviActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putDouble("currentLat", currentLatitude);
                        bundle.putDouble("currentLng", currentLongitude);
                        bundle.putDouble("targetLat", inspectioninfo.glat);
                        bundle.putDouble("targetLng", inspectioninfo.glng);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });

                return view;
            }

        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };

    //点击marker就消失
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 108) {
            String imel = data.getStringExtra("IMEI");
            getCarinfo(imel);
        }
    }

    final AMap.OnMapClickListener listeners = new AMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            clickMaker.hideInfoWindow();
        }
    };

    //获得车辆信息
    private void getCarinfo(String number) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        StringBuilder carStatsuBulider = new StringBuilder();
        carStatsuBulider.append(SharedUtil.getUrl()).append(Url.BOX_STATUS);
        XHttpRequest.getInstance().postRequests(carStatsuBulider.toString(), jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(VehicleInspectionActivity.this, R.style.activity_dialog);
                                View view = LayoutInflater.from(VehicleInspectionActivity.this).inflate(R.layout.vehicleinspection_dialog, null);
                                final AlertDialog inspectionDialog = builder.create();
                                inspectionDialog.setView(view);
                                inspectionDialog.show();
                                final TextView numbers = view.findViewById(R.id.number);
                                TextView address = view.findViewById(R.id.address);
                                TextView batterys = view.findViewById(R.id.batterys);
                                numbers.setText(jsonObject.optJSONObject("data").optString("number"));
                                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("city_path"))) {
                                    address.setText("未知地址");
                                } else {
                                    address.setText(jsonObject.optJSONObject("data").optString("city_path"));
                                }
                                batterys.setText(jsonObject.optJSONObject("data").optString("battery"));
                                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(jsonObject.optJSONObject("data").optDouble("glat"), jsonObject.optJSONObject("data").optDouble("glng")), 15f));
                                final Button startdenfense = view.findViewById(R.id.startdefense_btn);
                                Button withdrawdevice = view.findViewById(R.id.withdrawdevice_btn);
                                Button oppaccBtn = view.findViewById(R.id.oppacc_btn);
                                Button playBtn = view.findViewById(R.id.play_btn);
                                Button gpsBtn = view.findViewById(R.id.gps_btn);
                                startdenfense.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {//撤防
                                        sendCommand(numbers.getText().toString(), "0", "3", "2");
                                    }
                                });
                                withdrawdevice.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {//设防
                                        sendCommand(numbers.getText().toString(), "1", "3", "6");
                                    }
                                });
                                oppaccBtn.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        sendCommand(numbers.getText().toString(), "0", "5", "4");
                                    }
                                });
                                playBtn.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        sendCommand(numbers.getText().toString(), "0", "1", "5");
                                    }
                                });
                                gpsBtn.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        sendCommand(numbers.getText().toString(), "0", "9", "");
                                    }
                                });
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast("获取车辆信息失败");
            }
        });
    }

    //统一下发指令,第一参数是车辆编号，第二个开关,第三个是什么类型指令，第四个是蓝牙命令类型
    private void sendCommand(final String number, final String sw, final String type, final String blueCommandType) {
        showLoadingDialog("正在下发命令...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "0");
        StringBuilder sendCommandBulider = new StringBuilder();
        sendCommandBulider.append(SharedUtil.getUrl()).append(Url.QUERYVEHCLES);
        XHttpRequest.getInstance().postRequests(sendCommandBulider.toString(), jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (jsonObject.optString("data").equals("{}")) {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(VehicleInspectionActivity.this, R.style.activity_dialog);
                                    View view = LayoutInflater.from(weakReferenceContext.get()).inflate(R.layout.blue_endcar_dialog, null);
                                    final AlertDialog conituredialog = builder.create();
                                    conituredialog.setView(view);
                                    conituredialog.show();
                                    final TextView contents = view.findViewById(R.id.content);
                                    final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                    final Button cancel = view.findViewById(R.id.cancel);
                                    contents.setText(jsonObject.optString("message"));
                                    cancel.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            conituredialog.dismiss();
                                        }
                                    });
                                    endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            conituredialog.dismiss();
                                            if (!mBlueadapter.isEnabled()) {
                                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                            } else {
                                                connectBlueTeeth(number, jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"), blueCommandType);
                                            }

                                        }
                                    });

                                }
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //蓝牙连接，第一个参数暂时无用，第二个设备编号，第三个密钥，第四个作为不同功能指令区分
    private void connectBlueTeeth(final String number, String devices, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙中");
        TbitBle.connect(devices, token, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                if (resultCode == 0) {
                    switch (blueCommandType) {
                        case "1": //启动
                            unlockDevice(number);
                            break;
                        case "2": //撤防
                            defenseCloseBlueteethDevice(number);

                            break;
                        case "3": //关闭
                            defenseBlueteethDevice(number,"1");
                            break;
                        case "4": //开仓
                            openAccBlueteethDevice(number);
                            break;
                        case "5": //播报
                            findCarBlueteethDevice(number);

                            break;
                        case "6": //设防
                            defenseBlueteethDevice(number,"2");
                            break;
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast("错误码: " + resultCode + " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {
                dismissLoadingDialog();

            }
        });
    }

    //开仓蓝牙命令
    private void openAccBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x05, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        dismissLoadingDialog();
                        // 发送状态回复
                        if (resultCode == 0) {
                            sendCommandWithBlueTeeth(number, "0", "5");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    //播报(寻车)蓝牙命令
    private void findCarBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x04, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        dismissLoadingDialog();
                        if (resultCode == 0) {
                            sendCommandWithBlueTeeth(number, "0", "1");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    //设防开启蓝牙命令
    private void defenseBlueteethDevice(final String number, final String type) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x01}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                if (resultCode == 0) {
                    if (type.equals("1")) {
                        sendCommandWithBlueTeeth(number, "0", "2");
                    }else {
                        sendCommandWithBlueTeeth(number, "1", "3");
                    }
                } else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
                // 收到packet回复
            }
        });

    }

    //撤防蓝牙命令
    private void defenseCloseBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x00}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 发送状态回复
                dismissLoadingDialog();
                if (resultCode == 0) {
                    sendCommandWithBlueTeeth(number, "0", "3");
                } else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
                // 收到packet回复
            }
        });
    }

    // 解锁
    private void unlockDevice(final String number) {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                // 解锁回应
                if (resultCode==0){
                    sendCommandWithBlueTeeth(number, "1", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请稍候再试");
                }

            }
        });
    }


    private void sendCommandWithBlueTeeth(String number, String sw, String type) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "1");//是否通过蓝牙开锁：0否，1是
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    public void connectBlueTeeth(final String number, String imei, final String xaCommandType) {
        showLoadingDialog("正在连接蓝牙中...");
        if (null != apiClient) {
            apiClient.connectToIMEI(imei);
        }
        builder.setBleStateChangeListener(new BleStateChangeListener() {
            @Override
            public void onConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (xaCommandType) {
                            case "1": //启动
                                setAcc(number);
                                break;
                            case "2": //撤防
                                setundefend(number);
                                break;
                            case "3": //关闭
                                setAccOff(number);
                                break;
                            case "4": //开仓
                                setsaddle(number);
                                break;
                            case "5": //播放
                                findcar(number);
                                break;
                                default:
                                    break;
                        }

                    }
                });
            }

            @Override
            public void onDisConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        Log.e("蓝牙连接失败", "蓝牙连接失败");
                        ToastUtil.showToast("蓝牙连接失败,请重新连接");
                    }
                });
            }

            @Override
            public void onDeviceReady(BluetoothDevice bluetoothDevice) {
            }

            @Override
            public void onReadRemoteRssi(int i) {
            }

            @Override
            public void onError(BluetoothDevice bluetoothDevice, String s, int i) {
            }

            @Override
            public void onBleAdapterStateChanged(int i) {
            }
        });
    }


    public void shutdown() {//关闭
        apiClient.shutdown(new BleCallback() {
            @Override
            public void onResponse(Response response) {
                Log.e("shutdown", response.toString());
            }
        });
    }

    //寻车
    public void findcar(final String number) {
        apiClient.findCar(new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "1");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        });
    }

    //电门开
    public void startacc() {
        apiClient.setAcc(true, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                Log.e("电门开 : ", response.toString());

            }
        });
    }

    //电门关
    public void startunacc() {
        apiClient.setAcc(false, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                Log.e("电门关 : ", response.toString());
            }
        });
    }

    //设防
    public void setdefend() {
        apiClient.setDefend(true, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                Log.e("设防 : ", response.toString());

            }
        });
    }

    //撤防
    public void setundefend(final String number) {
        apiClient.setDefend(false, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "3");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        });
    }


    //电池仓开
    public void setsaddle(final String number) {
        apiClient.setSaddle(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "5");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        });
    }

    //电池仓关
    public void setsaddleoff() {
        apiClient.setSaddle(false, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                Log.e("saddle: ", response.toString());
            }
        });
    }

    public void setAcc(final String number) {
        apiClient.setAcc(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "1", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }

            }
        });
    }

    public void setAccOff(final String number) {
        apiClient.setAcc(false, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请重新再试");
                }
            }
        });
    }



    class LoadPageAdapter extends PagerAdapter {//

        @Override
        public int getCount() {
            if (titlesArray == null) {
                return 0;
            }
            if (titlesArray.size() == 1) {
                return titlesArray.size();
            } else {
                return Integer.MAX_VALUE;//无限轮播
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            View view = LayoutInflater.from(VehicleInspectionActivity.this).inflate(R.layout.dialog_vehicle_violation_item, container, false);
            if (titlesArray.size() > 0) {
                final int newPostion = position % titlesArray.size();
                TextView violationTxt = view.findViewById(R.id.violation_txt);
                violationTxt.setText(titlesArray.get(newPostion));
                Button dealBtn = view.findViewById(R.id.deal_btn);
                dealBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                    }
                });

            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    public void callPhone(String phoneNum) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(VehicleInspectionActivity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                ActivityCompat.requestPermissions(VehicleInspectionActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

}
